new Vue({
    el: '#app',
    data() {
        return {
            form: {},
            Store_SerialNumber: '',//店铺/中心点
            Department_SerialNumber: '',//小区
            radius: 400,
            loading: false,
            center: null,//店铺
            center1: null,//小区点
            canvasGroundLayer: null,//圆形覆盖区域
            Store_Marker: null,//地图中心点
            Department_Marker: null,//小区点
            map: null,
            distance: 0,
        }
    },
    mounted() {
        if (getCookie('role')) {
            let roleObj = JSON.parse(getCookie('role'));
            this.Store_SerialNumber = roleObj.other;
        }
        this.Department_SerialNumber = sessionStorage.getItem("Department_SerialNumber")
        this.getData();
    },
    methods: {
        getData() {//逆地址解析
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data: {
                    SQLSerialNumber: "P_business_store_info",
                    Condition: window.btoa(unescape(encodeURIComponent('%%'))),
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(" and business_store_info.Store_SerialNumber='" + this.Store_SerialNumber + "'"))),
                },
                success: (data) => {
                    if (data.length > 0) {
                        that.Store_Name = data[0].Store_Name;
                        that.radius = Number(data[0].Region);
                        $.ajax({
                            url: `${BASE_URL1}/getAddressResolutionAction?grant_type=tourist`,
                            type: 'POST',
                            data: {
                                Address: data[0].Province + data[0].City + data[0].County + data[0].Store_Address
                            },
                            success: (res) => {
                                if (res.Status == 'success') {
                                    that.center = new TMap.LatLng(res.Data.lat, res.Data.lng);
                                    that.initMap();
                                }
                            },
                        })
                    } else {
                        this.$message.error('店铺获取失败');
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        initMap() {
            const that = this;
            // 初始化地图
            this.map = new TMap.Map(this.$refs.container, {
                zoom: 15, // 设置地图缩放级别
                center: this.center, // 设置地图中心点坐标
            });
            // 初始化圆形覆盖物
            this.canvasGroundLayer = new TMap.MultiCircle({
                map: this.map,
                style: {
                    color: 'rgba(41,91,255,0.16)', // 填充颜色
                    borderColor: 'rgba(41,91,255,1)', // 边框颜色
                    borderWidth: 2, // 边框宽度
                    borderOpacity: 1, // 边框透明度
                    fillOpacity: 0.2, // 填充透明度
                },
                geometries: [{
                    styleId: 'circle',
                    center: this.center,
                    radius: this.radius, //半径  1000包含
                }],

            });
            this.Store_Marker = new TMap.MultiMarker({
                map: this.map,
                styles: {
                    marker: new TMap.MarkerStyle({
                        width: 20, // 样式宽
                        height: 30, // 样式高
                    })
                },
                geometries: [{
                    styleId: 'marker',
                    position: this.center,
                }],
            });
            //初始化infoWindow
            const infoWindow = new TMap.InfoWindow({
                map: this.map,
                position: this.center, //设置信息框位置
                offset: { x: 0, y: -30 },
                content: this.Store_Name //设置信息框内容
            });
            this.Store_Marker.on("click", function (evt) {
                //设置infoWindow
                infoWindow.open(); //打开信息窗
                infoWindow.setPosition(evt.geometry.position);//设置信息窗位置
                infoWindow.setContent(that.Store_Name);//设置信息窗内容
            })
            this.getDepartment();
        },
        getDepartment() {//获取小区
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumberWithOriginal`,
                type: 'POST',
                data: {
                    SQLSerialNumber: "P_business_department_info",
                    Condition: '',
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(" and business_department_info.Department_SerialNumber='" + this.Department_SerialNumber + "'"))),
                },
                success: (data) => {
                    if (data.length > 0) {
                        that.form = data[0];
                        $.ajax({
                            url: `${BASE_URL1}/getAddressResolutionAction?grant_type=tourist`,
                            type: 'POST',
                            data: {
                                Address: data[0].Province + data[0].City + data[0].County + data[0].Store_Address
                            },
                            success: (res) => {
                                if (res.Status == 'success') {
                                    that.center1 = new TMap.LatLng(res.Data.lat, res.Data.lng);
                                    that.createMarker();
                                }
                            },
                        })

                    } else {
                        this.$message.error('小区获取失败');
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        createMarker() {
            const that = this;
            this.Department_Marker = new TMap.MultiMarker({
                map: this.map,
                styles: {
                    marker: new TMap.MarkerStyle({
                        width: 20, // 样式宽
                        height: 30, // 样式高
                    })
                },
                geometries: [{
                    styleId: 'marker',
                    position: this.center1,
                }],
            });
            const infoWindow = new TMap.InfoWindow({
                map: this.map,
                position: this.center1, //设置信息框位置
                offset: { x: 0, y: -30 },
                content: this.form.Department_Name //设置信息框内容
            });
            this.Department_Marker.on("click", function (evt) {
                //设置infoWindow
                infoWindow.open(); //打开信息窗
                infoWindow.setPosition(evt.geometry.position);//设置信息窗位置
                infoWindow.setContent(this.form.Department_Name);//设置信息窗内容
            })
            //自适应显示到一个地图下
            let bounds = new TMap.LatLngBounds();
            let markerArr = [this.center, this.center1];
            markerArr.forEach(item => {
                if (bounds.isEmpty() || !bounds.contains(item)) {
                    bounds.extend(item);
                }
            })
            this.map.fitBounds(bounds, {
                padding: 100 // 自适应边距
            });
            //画线
            const line = new TMap.MultiPolyline({
                map: this.map,//绘制到目标地图
                //折线样式定义
                styles: {
                    'style_blue': new TMap.PolylineStyle({
                        'color': '#3777FF', //线填充色
                        'width': 3, //折线宽度
                        'lineCap': 'butt' //线端头方式
                    }),
                },
                //折线数据定义
                geometries: [{
                    'id': 'pl_1',//折线唯一标识，删除时使用
                    'styleId': 'style_blue',//绑定样式名
                    'paths': [this.center, this.center1]
                }]
            });
            $.ajax({
                url: `${BASE_URL1}/haversineDistance`,
                type: 'POST',
                data: {
                    Data: JSON.stringify([{ lat: this.center.lat, lon: this.center.lng }, { lat: this.center1.lat, lon: this.center1.lng }])
                },
                success: (res) => {
                    if (res.Status == 'success') {
                        that.distance = res.Data;
                        //初始化infoWindow
                        const infoWindow = new TMap.InfoWindow({
                            map: this.map,
                            position: new TMap.LatLng((this.center.lat + this.center1.lat) / 2, (this.center.lng + this.center1.lng) / 2), //设置信息框位置
                            content: '店铺经营范围' + that.radius + '米,当前距离' + parseInt(res.Data) + '米' //设置信息框内容
                        });
                        line.on("click", function (evt) {
                            infoWindow.open(); //打开信息窗
                            infoWindow.setContent('店铺经营范围' + that.radius + '米,当前距离' + parseInt(res.Data) + '米');//设置信息窗内容
                        })
                    }
                },
                dataType: "json"
            })
        },
        submitForm() {
            const that = this;
            this.loading = true
            this.form.Store_SerialNumber = this.Store_SerialNumber;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data: {
                    Data: JSON.stringify({
                        Modify: { business_department_info: [that.form] },
                    })
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        that.$message.success("提交成功")
                        window.history.go(-1)
                    } else {
                        that.$message.error("提交失败，请稍后再试")
                    }
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        }
    },
})